<template>
  <div class="nowState">
    <div class="searchDiv">
      <Form :model="searchItem" :label-width="90">
        <Row :gutter="10">
          <Col span="6">
                    <FormItem label="电站">
                    <Select v-model="searchItem.powerStation" clearable filterable @on-change="getHd">
                        <Option v-for="(item, index) in powerStationList" :value="item" :key="index">{{item}}</Option>
                    </Select>
                    </FormItem>
           </Col>
           <Col span="6">
            <FormItem label="HD编号">
              <Select v-model="searchItem.hdNumber" clearable filterable :disabled="HBnumberList.length==0" @on-change="getJz">
                  <Option v-for="(item, index) in HBnumberList" :value="item" :key="index">{{item}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="机组编号">
               <Select v-model="searchItem.aircrewNumber" clearable filterable :disabled="JZnumberList.length==0">
                  <Option v-for="(item, index) in JZnumberList" :value="item" :key="index">{{item}}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
                    <FormItem label="类型">
                      <Select v-model="searchItem.alarmAlias" clearable filterable>
                          <Option value="开机" :key="1">开机</Option>
                          <Option value="停机" :key="2">停机</Option>
                      </Select>
                    </FormItem>
           </Col>
           <Col span="6">
                    <FormItem label="机组状态">
                     <Select v-model="searchItem.statusDictId" clearable filterable @on-change="getSelect1">
                          <Option v-if="searchItem.alarmAlias=='开机'" v-for="(item, index) in JZstatusList" :value="item.id" :key="index">{{item.displayName}}</Option>
                          <Option v-if="searchItem.alarmAlias=='停机'" v-for="(item, index) in JZstatusList2" :value="item.id" :key="index+100">{{item.displayName}}</Option>
                      </Select>
                    </FormItem>
           </Col>
          <Col span="6">
            <FormItem label="状态变更时刻">
              <DatePicker
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                @on-change="handleChangeSearchClock"
                placeholder="选择日期和时间"
                style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="12">
            <Button type="primary" @click="searchItem.pageNo=1;search()" class="marRight">查询</Button>
            <Button type="success" class="marRight" @click="add">新增状态</Button>
            <Button type="primary" @click="down">导出Excel</Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table :loading="loading" border :columns="columns" :data="tableData"></Table>
    <Page show-total :total="total" show-elevator :page-size='searchItem.pageSize' :current="searchItem.pageNo" @on-change='pageChange'  style="margin:20px auto;text-align:center"/>
    <!-- 新增弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal1"  :title="title1" width="1000" >
      <div class="baseTitle">基本信息</div>
           <Form :label-width="100">
             <Row :gutter="10" class="xzjz">
                 <Col span="8">
                    <FormItem  label="电站：">
                     <Select v-if="editState==false" v-model="formItem.powerStation" clearable filterable @on-change="getHd2">
                        <Option v-for="(item, index) in powerStationList2" :value="item" :key="index">{{item}}</Option>
                    </Select>
                     <Input v-if="editState" v-model="formItem.powerStation" disabled></Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="HD编号：">
                     <Select v-if="editState==false" v-model="formItem.hdNumber" clearable filterable :disabled="HBnumberList2.length==0" @on-change="getJz2">
                        <Option v-for="(item, index) in HBnumberList2" :value="item" :key="index">{{item}}</Option>
                    </Select>
                     <Input v-if="editState" v-model="formItem.hdNumber" disabled></Input>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="机组编号：">
                        <Select v-if="editState==false" v-model="formItem.aircrewNumber" clearable filterable :disabled="JZnumberList2.length==0">
                          <Option v-for="(item, index) in JZnumberList2" :value="item" :key="index">{{item}}</Option>
                      </Select>
                       <Input v-if="editState" v-model="formItem.aircrewNumber" disabled></Input>
                    </FormItem>
                  </Col>
             </Row>
           </Form>
           <div class="baseTitle">状态信息</div>
           <Form :label-width="100">
             <Row :gutter="10" class="xzjz">
                 <Col span="8">
                    <FormItem label="类型：">
                      <Select v-model="formItem.alarmAlias" clearable filterable>
                          <Option value="开机" :key="1">开机</Option>
                          <Option value="停机" :key="2">停机</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <!-- <Col span="8">
                    <FormItem label="类型：">
                        <span v-if="formItem.alarmAlias=='正常'||formItem.alarmAlias=='危险'||formItem.alarmAlias=='报警'">开机</span>
                        <span v-if="formItem.alarmAlias=='停机'||formItem.alarmAlias=='停车'||formItem.alarmAlias=='断网'">停机</span>

                    </FormItem>
                  </Col> -->
                  <Col span="8">
                    <FormItem label="机组状态：">
                      <!-- <Select v-model="formItem.status">
                        <Option value="全部">全部</Option>
                        <Option value="测试">测试</Option>
                     </Select> -->
                     <Select v-model="formItem.statusDictId" clearable filterable @on-change="getSelect2">
                          <Option v-show="formItem.alarmAlias=='开机'" v-for="(item, index) in JZstatusList" :value="item.id" :key="index">{{item.displayName}}</Option>
                          <Option v-show="formItem.alarmAlias=='停机'" v-for="(item, index) in JZstatusList2" :value="item.id" :key="index+100">{{item.displayName}}</Option>
                      </Select>
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="状态变更时刻：">
                      <DatePicker
                      type="datetime"
                      :disabled="editState"
                      v-model="formItem.statusUpdateTime"
                      format="yyyy-MM-dd HH:mm:ss"
                      @on-change="handleChangeFromClock"
                      :options="optionsTime"
                      placeholder="选择日期"
                      style="width: 100%"
                    ></DatePicker>
                    </FormItem>
                  </Col>
                  <!-- <Col span="8">
                    <FormItem label="累计运行时间：">
                      <Input v-model="formItem.runningTime" placeholder="累计运行时间(小时)"></Input>
                    </FormItem>
                  </Col> -->
               </Row>
           </Form>
           <Form :label-width="100">
             <Row :gutter="10" class="xzjz">
                  <div class="baseTitle">填报信息</div>
                  <Col span="8">
                    <FormItem label="记录人：">
                      <Input v-model="recordName" disabled placeholder="请输入"></Input>
                      <!-- <Select @on-change="jiluName" v-model="formItem.recordId" label-in-value clearable filterable>
                          <Option v-for="(item, index) in peopleList" :value="item.id" :key="index">{{item.trueName}}</Option>
                      </Select> -->
                    </FormItem>
                  </Col>
                  <Col span="8">
                    <FormItem label="记录时间：">
                      <!-- <DatePicker
                        type="datetime"
                        v-model="formItem.recordTime"
                        @on-change="handleChangeFormRecordTime"
                        placeholder="记录时间"
                        style="width: 100%"
                      ></DatePicker> -->
                      <Input v-model="recordTime" disabled placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
             </Row>
           </Form>
           <div slot="footer">
               <Button @click="modal1=false">取消</Button>
              <Button type="primary" :loading="btnClick" @click="ok">确定</Button>
          </div>
    </Modal>
    <Modal :mask-closable="false" v-model="modal2" width="360" class-name="vertical-center-modal" @on-ok="remove(delIndex)">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>确认删除</span>
        </p>
        <div style="text-align:center">
            <p>确认删除此数据么？</p>
        </div>
    </Modal>
    <!-- 新增弹窗结束 -->
  </div>
</template>

<script>

import {
  addAircrewStatusRecord,
  searchAircrewStatusRecord,
  removeAircrewStatusRecord,
  updateAircrewStatusRecord,
  downExcel
} from '@/api/runManage'
import {
  getSelectOption,
  getAllPeople,getTime,getAllEqu
} from '@/api/select'
export default {
  data () {
    return {
      btnClick:false,
      time:Date.now(),
      optionsTime:{
        disabledDate: date => {
          return date && date.valueOf() > this.time
        }
      },
      loading:true,
      editState:false,
      recordName: localStorage.getItem('recordUserName'),
        recordId:localStorage.getItem('recordUserId'),
        recordTime:getTime(),
      total: 0,
      modal1: false,
      title1: '新增记录',
      peopleList:[],
      allEquList:[],
      allEquList2:[],
      allEquList3:[],
      allEquList4:[],
      powerStationList:[],
      HBnumberList:[],
      JZnumberList:[],
      powerStationList2:[],
      HBnumberList2:[],
      JZnumberList2:[],
      JZstatusList:[],
      JZstatusList2:[],
      LeibieList:[],
      searchItem: {
        pageNo: 1,
        pageSize: 10
      },
      delIndex: 0,
      modal2: false,
      formItem: {
      },
      columns: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center'
        },
        {
          title: '电站',
          key: 'powerStation'
        },
        {
          title: 'HD编号',
          key: 'hdNumber'
        },
        {
          title: '机组编号',
          key: 'aircrewNumber'
        },
        {
          title: '类型',
          key: 'alarmAlias',
          render: (h, params) => {
            let state=''
            if(params.row.alarmAlias=='正常'||params.row.alarmAlias=='危险'||params.row.alarmAlias=='报警'||params.row.alarmAlias=='开机'){
              state='开机'
            } else {
              state='停机'
            }
            return h('div', state)
          }
        },
        {
          title: '机组状态',
          key: 'statusDisplayName'
        },
        {
          title: '状态变更时刻',
          key: 'statusUpdateTime'
        },
        {
          title: '累计运行时间(小时)',
          key: 'runningTime',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div',(params.row.runningTime/(1000*3600)).toFixed(2)+'小时')
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              // h(
              //   'Button',
              //   {
              //     props: {
              //       type: 'primary',
              //       size: 'small'
              //     },
              //     style: {
              //       marginRight: '5px'
              //     },
              //     on: {
              //       click: () => {
              //         this.edit(JSON.stringify(params));
              //       }
              //     }
              //   },
              //   '处理'
              // ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small',
                    disabled:params.row.monitorWay!='2'
                  },
                  on: {
                    click: () => {
                      this.openDel(params.row.id)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      tableData: []
    }
  },
  created () {

  },
  methods: {
    down(){
      downExcel(this.searchItem).then(res => {
         const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, '机组当前状态.xlsx');
        } else {
            const url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', '机组当前状态.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
      })
    },
     getSelect1(e){
       let newarry=this.JZstatusList.concat(this.JZstatusList2);
       var arry=newarry.filter(item => item.id==e)
       this.searchItem.statusDisplayName=arry[0].displayName
       this.searchItem.statusValue=arry[0].value
    },
    getSelect2(e){
       let newarry=this.JZstatusList.concat(this.JZstatusList2);
       var arry=newarry.filter(item => item.id==e)
       this.formItem.statusDisplayName=arry[0].displayName
       this.formItem.statusValue=arry[0].value
    },
    jiluName(e){
      this.formItem.recordName=e.label
    },
    pageChange (e) {
      this.searchItem.pageNo = e
      console.log(this.searchItem.pageNo, '页码')
      this.search()
    },
    handleChangeSearchStateTime (e) {
      console.log(e)
    },

    handleChangeFromClock (e) {
      this.formItem.statusUpdateTime = e
    },

    handleChangeFormRecordTime (e) {
      this.formItem.recordTime = e
    },

    handleChangeSearchClock (e) {
      this.searchItem.startStatusUpdateTime = e[0];
      this.searchItem.endStatusUpdateTime = e[1];
    },
    //获取所有人员
    getAllPeople(){
      getAllPeople(
        null
      ).then(res => {
        this.peopleList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
     // 获取电站类型列表
    // powerStation () {
    //   getSelectOption(
    //     {
    //       code: 'dianzhan'
    //     }
    //   ).then(res => {
    //     this.powerStationList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // HBnumber () {
    //   getSelectOption(
    //     {
    //       code: 'hd_code'
    //     }
    //   ).then(res => {
    //     this.HBnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // JZnumber () {
    //   getSelectOption(
    //     {
    //       code: 'jizu_code'
    //     }
    //   ).then(res => {
    //     this.JZnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    JZstatus () {
      getSelectOption(
        {
          code: 'jizhu_status'
        }
      ).then(res => {
        this.JZstatusList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
      getSelectOption(
        {
          code: 'jizhu_status2'
        }
      ).then(res => {
        this.JZstatusList2 = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    Leibie () {
      getSelectOption(
        {
          code: 'catory'
        }
      ).then(res => {
        this.LeibieList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },

    remove (id) {
      removeAircrewStatusRecord({ id }).then(res => {
        console.log('delete success: ' + id, res)
        this.$Message.info('删除成功')
        this.searchItem.pageNo=1
        this.search()
      }).catch(err => {
        console.log(err)
      })
    },
    add () {
      this.title1 = '新增状态'
      this.modal1 = true;
      this.editState=false;
      this.formItem={};
    },
    openDel (index) {
      this.modal2 = true
      this.delIndex = index
      // this.remove(params.index);
    },
    edit (params) {
      this.title1 = '编辑状态'
      this.formItem = JSON.parse(params).row
      this.modal1 = true;
      this.editState=true;
      if(this.formItem.alarmAlias=='正常'||this.formItem.alarmAlias=='危险'||this.formItem.alarmAlias=='报警'){
        this.JZstatusList2=this.JZstatusList.filter(item => item.displayName==='月度试验'||item.displayName==='维修' )
      }
      if(this.formItem.alarmAlias=='停机'||this.formItem.alarmAlias=='断网'){
        this.JZstatusList2=this.JZstatusList.filter(item => item.displayName==='备用'||item.displayName==='不可用' )
      }
    },
    ok () {
      this.btnClick=true;
      this.formItem.recordName=this.recordName;
      this.formItem.recordId=this.recordId;
      this.formItem.recordTime=this.recordTime;
      if (this.title1 == '新增状态') {
        addAircrewStatusRecord(this.formItem).then((res) => {
          console.log('data：', this.formItem)
          console.log('add success： ', res)
          if (res.code == 0) {
            this.$Message.info('新增成功')
            this.search()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.btnClick=false;
            this.$Message.info(res.message)
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
          this.loading3 = false
        })
      } else {
        let newform={
          id:this.formItem.id,
          statusDictId:this.formItem.statusDictId,
          statusDisplayName:this.formItem.statusDisplayName,
          statusValue:this.formItem.statusValue
        }
        updateAircrewStatusRecord(newform).then(res => {
          if (res.code == 0) {
            this.$Message.info('修改成功')
            this.search()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.btnClick=false;
            this.$Message.info(res.message)
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      }
    },
    search () {
      console.log(this.searchItem)
      searchAircrewStatusRecord(this.searchItem).then(res => {
        console.log('get search:', res)
        this.tableData = res.data.list
        this.total = res.data.total
        this.loading=false
        if (res.code == 0) {

        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getAllEqument(){
     getAllEqu(null).then(res => {
        this.allEquList=res.data;
        let arr = res.data.map(function(item) {
              return item.powerStation;
        });
        this.powerStationList=[...new Set(arr)]

        this.allEquList3=res.data.filter(
        item =>item.monitorWay != 3
        );
        let arr2 = this.allEquList3.map(function(item) {
              return item.powerStation;
        });
        this.powerStationList2=[...new Set(arr2)]

      })
    },
    getHd(e){
      this.JZnumberList=[];
      this.allEquList2=this.allEquList.filter(
        item =>item.powerStation == e
      );
      let arr2=this.allEquList2.map(function(item) {
        return item.hdNumber;
      });
      this.HBnumberList=[...new Set(arr2)];
    },
    getJz(e){
      let arr=this.allEquList2.filter(
        item =>item.hdNumber == e
      );
      let arr2=arr.map(function(item) {
        return item.aircrewNumber;
      });
      this.JZnumberList=[...new Set(arr2)];
    },
    getHd2(e){
      this.JZnumberList2=[];
      this.allEquList4=this.allEquList3.filter(
        item =>item.powerStation == e
      );
      let arr2=this.allEquList4.map(function(item) {
        return item.hdNumber;
      });
      this.HBnumberList2=[...new Set(arr2)];
    },
    getJz2(e){
      let arr=this.allEquList4.filter(
        item =>item.hdNumber == e
      );
      let arr2=arr.map(function(item) {
        return item.aircrewNumber;
      });
      this.JZnumberList2=[...new Set(arr2)];
    }
  },
  mounted () {
    this.getAllEqument()
    this.JZstatus();
    this.Leibie();
    this.getAllPeople();
    this.search()
  }
}
</script>

<style lang="less">
.nowState {
  background: #fff;
  height: 100%;
  padding: 15px;
  font-size: 14px;
  .searchDiv {
    .marRight {
      margin-right: 15px;
    }
  }
  .ivu-form-item {
    margin-bottom: 15px;
  }
}
.baseTitle {
    font-weight: bold;
    font-size:16px;
    margin-bottom:10px;
  }
 .xzjz  {
   .ivu-form-item {
    margin-bottom: 10px;
  }
 }

  // .footer
</style>
